<template>
  <div class="pb30">
    <el-form
      class="fl"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
      @submit.native.prevent
    >
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="fr">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        v-hasPermi="['system:project:add']"
      >
        新增商品
      </el-button>
      <el-button
        type="warning"
        icon="el-icon-download"
        size="mini"
        @click="handleImport"
        v-hasPermi="['system:project:import']"
      >
        导入商品
      </el-button>
    </div>

    <el-table v-loading="loading" :data="list">
      <el-table-column prop="index" label="序号" align="center" width="80">
        <template slot-scope="scope">
          {{
            scope.$index + (queryParams.pageNum - 1) * queryParams.pageSize + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="图片" align="center" prop="picUrl">
        <template slot-scope="scope">
          <div v-if="scope.row.picUrl" class="demo-image__preview table-img">
            <el-image
              :src="scope.row.picUrl"
              :preview-src-list="[scope.row.picUrl]"
            >
            </el-image>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="spe" />
      <el-table-column label="进价" align="center" prop="myPrice">
        <template slot-scope="scope"> {{ scope.row.myPrice }} 元 </template>
      </el-table-column>
      <el-table-column label="售价" align="center" prop="price">
        <template slot-scope="scope"> {{ scope.row.price }} 元 </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:project:edit']"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="picUrl" ref="imgViod">
          <div
            v-if="form.picUrl"
            style="width: 100px; height: 100px; position: relative"
          >
            <div class="demo-image__preview w100-img">
              <el-image
                :src="form.picUrl"
                :preview-src-list="[form.picUrl]"
                class="avatar"
              >
              </el-image>
            </div>
            <i
              v-if="form.picUrl"
              class="el-icon-delete remove-img"
              @click="handleRemove"
            />
          </div>

          <el-upload
            v-else
            class="avatar-uploader"
            :action="uploadImgUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="规格" prop="spe">
          <el-input v-model="form.spe" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="进价" prop="myPrice">
          <el-input-number
            v-model="form.myPrice"
            placeholder="请输入进价"
            controls-position="right"
            class="tl"
            style="width: calc(100% - 40px)"
          />
          <span class="ml10">元</span>
        </el-form-item>
        <el-form-item label="销售价格" prop="price">
          <el-input-number
            v-model="form.price"
            placeholder="请输入销售价格"
            controls-position="right"
            class="tl"
            style="width: calc(100% - 40px)"
          />
          <span class="ml10">元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  listProject,
  getProject,
  addProject,
  updateProject,
} from "@/api/project/shop";

import { getToken } from "@/utils/auth";
import { listConfig } from "@/api/system/config";
export default {
  name: "Project",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 商品表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
      },

      // 表单参数
      form: {},

      // 表单校验
      rules: {
        proId: [{ required: true, message: "主键id不能为空", trigger: "blur" }],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        picUrl: [
          { required: true, message: "图片地址不能为空", trigger: "blur" },
        ],
        spe: [{ required: true, message: "规格不能为空", trigger: "blur" }],
        price: [{ required: true, message: "请输入销售价格", trigger: "blur" }],
        myPrice: [{ required: true, message: "请输入进价", trigger: "blur" }],
      },

      //上传商品图片
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/project/input",
      },
      modalUrl: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams)
        .then((response) => {
          this.list = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        proId: undefined,
        name: undefined,
        picUrl: undefined,
        spe: undefined,
        price: undefined,
        myPrice: undefined,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      getProject(row.proId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.proId != null) {
            updateProject(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addProject(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },

    //上传图片
    handleAvatarSuccess(res, file) {
      this.form.picUrl = res.data.url;
      this.$refs.imgViod.clearValidate();
    },

    /** 导入按钮操作 */
    handleImport() {
      // 获取模板
      this.getUserModal();
      this.upload.title = "商品导入";
      this.upload.open = true;
    },

    getUserModal() {
      var param = {
        configKey: "shop.modal",
      };
      listConfig(param).then((res) => {
        if (res.rows.length != 0) {
          this.modalUrl = res.rows[0].configValue;
        } else {
          this.modalUrl = "";
        }
      });
    },

    /** 下载模板操作 */
    importTemplate() {
      if (this.modalUrl) {
        let a = document.createElement("a");
        a.href = this.modalUrl;
        a.download = "商品数据模板";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        this.$modal.msg("暂无下载模板");
      }
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$modal.msgSuccess("导入成功");
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.getList();
      } else {
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if (response.msg) {
          this.$modal.msgError(response.msg);
        } else {
          this.$modal.msgError("导入失败，请重新导入");
        }
      }
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 删除图片
    handleRemove() {
      this.form.picUrl = "";
    },
  },
};
</script>
  